package algorithm.recursionAndbacktrack.permuation.p46;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;

class Solution_v3 {
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> permutations = new ArrayList<>();
        if (nums != null && nums.length > 0) {
            getPermutations(nums, permutations, new boolean[nums.length], new ArrayDeque<Integer>());
        }

        return permutations;
    }

    private void getPermutations(int[] nums, List<List<Integer>> permutations, boolean[] used, ArrayDeque<Integer> permutation) {
        if (permutation.size() == nums.length) {
            permutations.add(new ArrayList<>(permutation));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (!used[i]) {
                used[i] = true;
                permutation.addLast(nums[i]);
                getPermutations(nums, permutations, used, permutation);
                permutation.removeLast();
                used[i] = false;
            }
        }
    }

    public static void main(String[] args) {
        System.out.println(new Solution_v3().permuteUnique(new int[]{1, 2, 3}));
    }
}